<template>
  <div class="wrapper">
    <Form ref="filterForm" :model="filterForm" :label-width="105" class="form-group clearfix">
      <div class="form-items-group clearfix">
        <FormItem label="Tag" prop="tag" class="item">
          <Input v-model="filterForm.tag" placeholder="Enter something..." style="width: 200px"></Input>
        </FormItem>
        <FormItem label="UPC" prop="UPC" class="item">
          <Input v-model="filterForm.UPC" placeholder="Enter something..." style="width: 200px"></Input>
        </FormItem>
        <FormItem label="From PO" prop="fromPO" class="item">
          <Input v-model="filterForm.fromPO" placeholder="Enter something..." style="width: 200px"></Input>
        </FormItem>
      </div>
      <div class="form-items-group clearfix">
        <FormItem label="Confirrmed Date" class="item">
          <DatePicker type="datetimerange" v-model="filterForm.confirmedDate" format="yyyy-MM-dd" placeholder="From: YYYY-MM-DD   To: YYYY-MM-DD" style="width: 300px"></DatePicker>
        </FormItem>
        <div class="btn-group">
          <Button type="primary" size="large" @click="formSubmit('filterForm')">Go</Button>
          <Button size="large" style="margin-left: 8px" @click="formReset('filterForm')" >Reset</Button>
        </div>
      </div>
    </Form>

    <section class="data-operates data-operates-top">
      <div class="data-operates-group">
        <p>Create Manully:</p>
        <Button type="primary" size="large" :disabled="confirmBtnDisable" @click="createShipment" class="item">Create Shipment</Button>
      </div>
      <div class="data-operates-group">
        <p>Create by Excel:</p>
        <Button size="large" shape="circle" type="primary" @click="exportSelectedItemsFunc" class="item">Export Selected Items</Button>
        <Button size="large" shape="circle" type="primary"  @click="importItemsModal = true" class="item">Import Shipment</Button>
      </div>
    </section>
    <section class="table-size">
      <div class="table-size-cnt">
        Table size
        <Radio-group v-model="tableSize" type="button">
          <Radio label="large">large</Radio>
          <Radio label="default">medium(default)</Radio>
          <Radio label="small">small</Radio>
        </Radio-group>
      </div>
      <p class="items-remain" v-show="waitToShipData"><span class="item-num">{{ waitToShipData.length }}</span> Items Remain</p>
    </section>
    <section class="data-list">
      <Table border no-data-text :size="tableSize" :loading="tableDataloading" ref="waitToConfirm" :columns="tableColumns" :data="waitToShipData" @on-select="addSelectedItem"  @on-select-cancel="removeSelectedItem" @on-selection-change="allSelectedOperate" v-if="waitToShipData.length"></Table>
      <div v-show="notableDataTip">
        <Alert type="warning" class="no-data-alter">
          A warning prompt
          <template slot="desc">
            No data for wait to confirm!!
          </template>
        </Alert>
      </div>
    </section>

    <Modal v-model="importItemsModal" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>Import Item Confirmation Excel File</span>
      </p>
      <div style="text-align:center">
        <Upload
          ref="excelFileUploadForm"
          type="drag"
          :format="['xlsx']"
          :on-format-error="handleFormatError"
          action="http://mock-data-data-api/api/supplier-PO/wait-to-ship/excel-import" :before-upload="fileBeforeUpload"  :on-success="fileUploadSuccess" :on-error ="fileUploadError" :on-progress="fileUploadProgress">
          <div style="padding: 20px 0">
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p>Click or drag files here to upload</p>
          </div>
        </Upload>
      </div>
      <div slot="footer"></div>
    </Modal>

    <transition name="router-slid" mode="out-in">
      <div>
        <keep-alive>
          <router-view v-if="$route.meta.keepAlive"></router-view>
        </keep-alive>
        <router-view v-if="!$route.meta.keepAlive"></router-view>
      </div>
    </transition>
  </div>
</template>

<script>
  import {mapState, mapMutations} from 'vuex';
  import { modalInstance } from '@/components/mixin';
  import { getSupplierPO, searchWaitToShipItems, waitToShipExcelExport } from '@/api/index';
  export default {
  	name: 'WaitToShipWH',
    mixins: [ modalInstance ],
    data () {
  		return {
        tableDataloading: true,
        notableDataTip: false,
        tableSize: 'default',
  			waitToShipData: [],
        exportSelectedItems: [],
        importItemsModal: false,
        uploadExcelResponseData: [],
        filterForm: {
          tag: '',
          UPC: '',
          fromPO: '',
          confirmedDate: ''
        },
        confirmBtnDisable: true,
        currencyUnit: '$',
        tableColumns: [
          {
            type: 'selection',
            width: 60,
            align: 'center',
            fixed: 'left'
          },
          {
            title: 'Tag',
            align: 'center',
            width: 90,
            fixed: 'left',
            key: 'tag'
          },
          {
            title: 'UPC',
            align: 'center',
            minWidth: 125,
            fixed: 'left',
            key: 'UPC'
          },
          {
            title: 'From PO',
            align: 'center',
            minWidth: 150,
            key: 'from_PO'
          },
          {
            title: 'Confirmed Date',
            align: 'center',
            minWidth: 150,
            key: 'confirmed_date'
          },
          {
            title: 'Category',
            align: 'center',
            width: 160,
            key: 'category'
          },
          {
            title: 'Brand',
            align: 'center',
            minWidth: 130,
            key: 'brand'
          },
          {
            title: 'Product Code',
            width: 85,
            align: 'center',
            key: 'product_code'
          },
          {
            title: 'Product Name',
            minWidth: 185,
            key: 'product_name'
          },
          {
            title: 'Colour Code',
            width: 80,
            align: 'center',
            key: 'colour_code'
          },
          {
            title: 'Size',
            width: 65,
            align: 'center',
            key: 'size'
          },
          {
            title: 'Order QTY',
            width: 70,
            align: 'center',
            key: 'order_QTY'
          },
          {
            title: 'Exp. QTY',
            width: 70,
            align: 'center',
            key: 'Exp_QTY'
          },
          {
            title: 'Unit Price',
            align: 'center',
            width:110,
            key: 'unit_price',
            render: (h, params) => {
              return h('input', {
                domProps: {
                	type: 'text',
                  placeholder: 'Unit Price',
                  value: params.row.unit_price
                },
                style: {
                  width: '100%',
                  lineHeight: '25px',
                  textAlign: 'center'
                },
                props: {
                  value: params.row.unit_price
                },
                on: {
                  blur: (e) => {
                    let inputValue = e.target.value;
                    if (inputValue != '' && inputValue != params.row.unit_price) {
                      let unitPriceCurrencyUnit = inputValue.replace(/([1-9]\d*\.?\d*)|(0\.\d*[1-9])/ig, '');
                      params.row.unit_price = unitPriceCurrencyUnit ? inputValue : '$' + inputValue;
                      this.currencyUnit = unitPriceCurrencyUnit ? unitPriceCurrencyUnit : '$';
                      params.row._checked = true;
                      let calcPriceResultObj = this.calcPrice(params.row.unit_price, params.row.discount, params.row.special_discount, params.row.Exp_QTY);
                      params.row.net_price = calcPriceResultObj.netPrice ? this.currencyUnit + calcPriceResultObj.netPrice : '';
                      params.row.total_price = calcPriceResultObj.totalPrice ? this.currencyUnit + calcPriceResultObj.totalPrice : '';
                      params.row.net_price = this.currencyUnit + calcPriceResultObj.netPrice;
                      params.row.total_price = this.currencyUnit + calcPriceResultObj.totalPrice;
                      if (!calcPriceResultObj.netPrice) {params.row.unit_price = ''}
                      this.waitToShipData.splice(params.index, 1, params.row);
                    }
                  }
                }
              })
            }
          },
          {
            title: 'Discount',
            align: 'center',
            width:110,
            key: 'discount',
            render: (h, params) => {
              return h('input', {
                domProps: {
                  type: 'text',
                  placeholder: 'Discount',
                  value: params.row.discount ? parseFloat(params.row.discount) + '%' : '0%'
                },
                style: {
                  width: '100%',
                  lineHeight: '25px',
                  textAlign: 'center'
                },
                props: {
                  value: params.row.discount ? parseFloat(params.row.discount) + '%' : '0%'
                },
                on: {
                  blur: (e) => {
                  	if (e.target.value != params.row.discount) {
                      params.row.discount = parseFloat(e.target.value);
                      let calcPriceResultObj = this.calcPrice(params.row.unit_price, params.row.discount, params.row.special_discount, params.row.Exp_QTY);
                      params.row.net_price = calcPriceResultObj.netPrice ? this.currencyUnit + calcPriceResultObj.netPrice : '';
                      params.row.total_price = calcPriceResultObj.totalPrice ? this.currencyUnit + calcPriceResultObj.totalPrice : '';
                      this.waitToShipData.splice(params.index, 1, params.row);
                    }
                  }
                }
              })
            }
          },
          {
            title: 'Special Discount',
            align: 'center',
            minWidth:150,
            key: 'special_discount',
            render: (h, params) => {
              return h('input', {
                domProps: {
                  type: 'text',
                  placeholder: 'Special Discount',
                  value: params.row.special_discount ? parseFloat(params.row.special_discount) + '%' : '0%'
                },
                style: {
                  width: '100%',
                  lineHeight: '25px',
                  textAlign: 'center'
                },
                props: {
                  value: params.row.special_discount ? parseFloat(params.row.special_discount) + '%' : '0%'
                },
                on: {
                  blur: (e) => {
                  	if (e.target.value !== params.row.special_discount) {
                      params.row.special_discount = parseFloat(e.target.value);
                      let calcPriceResultObj = this.calcPrice(params.row.unit_price, params.row.discount, params.row.special_discount, params.row.Exp_QTY);
                      params.row.net_price = calcPriceResultObj.netPrice ? this.currencyUnit + calcPriceResultObj.netPrice : '';
                      params.row.total_price = calcPriceResultObj.totalPrice ? this.currencyUnit + calcPriceResultObj.totalPrice : '';
                    }
                    this.waitToShipData.splice(params.index, 1, params.row);
                  }
                }
              })
            }
          },
          {
            title: 'Net Price',
            width: 90,
            align: 'center',
            key: 'net_price'
          },
          {
            title: 'Total Price',
            width: 100,
            align: 'center',
            key: 'total_price'
          }
        ]
      }
    },
    computed:{
      ...mapState([ 'curWaitToShipData'])
    },
    created () {
      this.initTableData();
    },
    methods: {
      ...mapMutations([ 'RECORD_WAITTOSHIP', 'RECORD_CREATESHIP', 'RECORD_IMPORTSHIPMENTFORMDATA']),
      initTableData: function () {
        getSupplierPO('wait-to-ship').then(res => {
          this.$Loading.start();
          let resObj = res.data;
          if (!!resObj) {
            this.$Loading.finish();
            this.tableDataloading = false;
            this.waitToShipData =  resObj.data;
//            this.waitToShipData.push(resObj.data[0]);
          } else {
            this.$Loading.error();
            this.notableDataTip = true;
          }
        });
      },
      calcPrice (unitPrice, discount, specialDiscount, expQTY) {
      	let netPrice = 0, totalPrice = 0;
        if (!!unitPrice) {
          let unitPriceValue = unitPrice.match(/([1-9]\d*\.?\d*)|(0\.\d*[1-9])/ig)[0];
          if (unitPriceValue == '') {
//            this.modalInstance('error', 'Error', 'Please enter a valid price!');
          	return {
              netPrice: '',
              totalPrice: ''
            };
          }
          discount = discount ? discount : 0;
          specialDiscount = specialDiscount ? specialDiscount : 0;
          let unitPriceConversion = parseFloat(unitPriceValue);
          let discountValue = parseFloat(discount), specialDiscountValue = parseFloat(specialDiscount);
          let discountConversion = !!discount ? (1 - discountValue * 0.01) : 1;
          let specialDiscountConversion = !!specialDiscount ? (1 - specialDiscountValue * 0.01): 1;
          netPrice = ((unitPriceConversion * 10e6) * (discountConversion * 10e6) * (specialDiscountConversion * 10e6)) / 10e20;
          totalPrice = (( netPrice * 10e6) * parseInt(expQTY)) / 10e6;
        }
        return {
          netPrice,
          totalPrice
        }
      },
      exportSelectedItemsFunc () {
        this.exportSelectedItems = [];
        this.waitToShipData.forEach(data => {
          if (data._checked) {
            this.exportSelectedItems.push(data);
          }
        });
        if (this.exportSelectedItems.length == 0) {
          this.modalInstance('warning', 'warning', 'Please select item !');
          return;
        }
        this.exportSelectedItems.forEach(item => {
        	item.unit_price = item.unit_price ? item.unit_price : '$0';
        	item.discount = item.discount ? parseFloat(item.discount) + '%' : '0%';
        	item.special_discount = item.special_discount ? parseFloat(item.special_discount) + '%' : '0%';
          item.fullfillment = '';
          item.supplier_courier = '';
          item.dispatch_date = '';
          item.ETA = '';
          item.tracking_number = '';
          item.shipping_fee = '$0';
          item.invoice_number = '';
          item.invoice_date = '';
        });
        waitToShipExcelExport(this.exportSelectedItems).then(res => {
          this.$Loading.start();
          let resData = res.data;
          if (resData.status_code == 1) {
            this.$Loading.finish();
            this.$Message.success('Export excel success!');
            this.modalInstance('success', 'Success', 'Export file success!');
          } else {
            this.$Loading.error();
            this.$Message.error('Export excel fail!');
          }
        });
      },
      addSelectedItem(selection, row){
        selection.forEach((selectionItem) => {
          this.waitToShipData.forEach(data => {
            if (selectionItem.tag == data.tag) {
              data._checked = true;
            }
          })
        });
      },
      removeSelectedItem(selection, row) {
        this.waitToShipData.forEach((data, index) => {
          if (row.tag == data.tag) {
            delete data._checked;
            delete data.Exp_QTY;
            data.status_text = 'wait to update';
          }
        })
      },
      allSelectedOperate (selection) {
        let newWaitToConfirmDada;
        if (selection.length == 0) {
          this.confirmBtnDisable = true;
          newWaitToConfirmDada = []
          this.waitToShipData.forEach((data, index) => {
            delete data._checked;
            delete data.Exp_QTY;
            data.status_text = 'wait to update';
            newWaitToConfirmDada.push(data);
          });
          return false;
        } else if (selection.length == this.waitToShipData.length) {
          this.confirmBtnDisable = false;
          newWaitToConfirmDada = []
          this.waitToShipData.forEach(data => {
            data._checked = true;
            newWaitToConfirmDada.push(data);
          })
          return false;
        } else {
          this.confirmBtnDisable = false;
          return false;
        }
        this.waitToShipData = newWaitToConfirmDada;
      },
      createShipment() {
        let dataArray = [];
        let willSubmitDataArrray = [];
        this.submitTipMsg = [];
        this.waitToShipData.forEach((item, index) => {
          item.discount = item.discount ? parseFloat(item.discount) + '%' : '0%';
          item.special_discount = item.special_discount ? parseFloat(item.special_discount) + '%' : '0%';
          if (!item.total_price && item._checked) {
            dataArray.push(item);
            this.submitTipMsg.push(item);
          } else if (item.total_price && item._checked) {
            willSubmitDataArrray.push(item);
          } else {
            dataArray.push(item);
          }
        });
        if (this.submitTipMsg.length > 0) {
          let submitModalTipHTML = '<p>Please complete the price calculation</p>';
          this.submitTipMsg.forEach(item => {
            submitModalTipHTML += '<p>UPC: ' + item.UPC +'<p>'
          });
          this.modalInstance('error', 'error', submitModalTipHTML);
          this.$Message.error('Submit fail!');
          return;
        }
//        this.waitToShipData = dataArray;
        this.RECORD_WAITTOSHIP(this.waitToShipData);
        if (willSubmitDataArrray.length > 0) {
          this.RECORD_CREATESHIP(willSubmitDataArrray);
          this.$router.push('/supplier-PO/wait-to-ship-WH/create-shipment');
        } else {
          this.modalInstance('error', 'error', 'Please select item');
          this.$Message.error('Submit fail!');
          this.$Loading.error();
        }
      },
      formSubmit: function (name) {
        if (!this.filterForm.tag && !this.filterForm.UPC && !this.filterForm.fromPO) {
          this.$Message.error('Please enter search condition!');
        } else {
          searchWaitToShipItems(this.filterForm.UPC).then(res => {
            this.$Loading.start();
            let resData = res.data;
            if(resData.status_code == 1) {
              this.waitToShipData = resData.data;
              this.$Message.success('Submit success!');
              this.$Loading.finish();
            } else {
              this.$Message.error('Submit fail!');
              this.$Loading.error();
            }
          });
        }
      },
      formReset: function (name) {
        this.filterForm.confirmedDate = '';
        this.$refs[name].resetFields();
        this.initTableData();
      },

      fileBeforeUpload (file) {
        this.$refs.excelFileUploadForm.clearFiles();
      },
      fileUploadProgress (event, file, fileList) {
        console.log('fileUploadProgress',event)
        console.log('fileUploadProgress',file)
        console.log('fileUploadProgress',fileList)
      },
      fileUploadSuccess (response, file) {
        this.uploadExcelResponseData = response.data.shipment_items;
        this.RECORD_IMPORTSHIPMENTFORMDATA(response.data.invoice_detail);
        this.importItemsModal = false;
        this.$Message.success('File Upload Success');
        this.uploadExcelResponseData.forEach(resData => {
          this.waitToShipData.forEach((item, index) => {
            if (resData.tag == item.tag) {
              item._checked = true;
              item.Exp_QTY = resData.Exp_QTY;
              item.unit_price = resData.unit_price;
              item.discount = resData.discount;
              item.special_discount = resData.special_discount;
              item.net_price = resData.net_price;
              item.total_price = resData.total_price;
              this.waitToShipData.splice(index, 1, item);
            }
          })
        });
        setTimeout(() => {
          this.createShipment();
          this.confirmBtnDisable = false;
        }, 3500);
      },
      fileUploadError(error, file, fileList) {
        this.modalInstance('warning', 'warning', error);
      },
      handleFormatError (file) {
        this.modalInstance('error', 'The file format is incorrect', 'File format of ' + file.name + ' is incorrect, please select xlsx.');
      }
    },
    watch: {
      waitToShipData: function (val) {
        if (val.length == 0) {
          this.notableDataTip = true;
        }
        this.RECORD_WAITTOSHIP(val);
      },
      curWaitToShipData: function (val) {
        let alreadyCheckedItem = val.some(function (item) {
          return item._checked;
        });
        if (alreadyCheckedItem) {
          this.confirmBtnDisable = false;
        } else {
          this.confirmBtnDisable = true;
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../../../assets/sass/mixin';
  .form-group {
    margin:20px 0 35px;
    .ivu-form-item {
      margin-bottom: 0;
    }
    .btn-group {
      float: right;
      margin-right: 0;
    }
  }
  .data-operates-top {
    padding-top: 0;
    @include fj(flex-start);
    .data-operates-group {
      margin-right: 30px;
      @include fj(flex-start);
      p, .item {
        margin-right: 10px;
      }
    }
  }
  .form-items-group {
    width: 100%;
    .item {
      float: left;
      margin-bottom: 10px;
    }
    .btn-group {
      float: right;
      padding-right: 5%;
    }
  }
</style>
